# xml解析
from my_email import my_email
from xml.dom.minidom import parse, Element
import re


def xy_str_to_list(xy_str: str)->list[list[int]]:
    """
    把有坐标的文字转换为数组
    """
    ret: list[str] = re.findall(r"[\[](.+?)[\]]", xy_str)
    ret_list=[]
    for i in ret:
        tem=i.split(",")
        tem_list=[]
        for x in tem:
            tem_list.append(int(x))
        ret_list.append(tem_list)
    return ret_list

def get_xy_by_xy_list(xy_list:list[list[int]]):
    '''
    根据xy_list获得点击坐标
    '''
    x=int((xy_list[0][0]+xy_list[1][0])/2)
    y=int((xy_list[0][1]+xy_list[1][1])/2)
    return (x,y)

def get_parent_bounds_str(path:str,Attri_text:str):
    '''
    获取父节点的bounds字符串
    '''
    # 读取文件
    dom = parse(path)
    # 获取文档元素对象
    data: Element = dom.documentElement

    node = data.getElementsByTagName("node")
    for i in node:
        ret = i.getAttribute("text")
        if ret == Attri_text:
            xy_str = i.parentNode.getAttribute("bounds")
            return xy_str
    return None

def get_current_bounds_str(path:str,Attri_text:str):
    '''
    获取当前节点的bounds字符串
    '''
    # 读取文件
    dom = parse(path)
    # 获取文档元素对象
    data: Element = dom.documentElement

    node = data.getElementsByTagName("node")
    for i in node:
        ret = i.getAttribute("text")
        if ret == Attri_text:
            xy_str = i.getAttribute("bounds")
            return xy_str
    return None

def get_parent_bounds_xy(path:str,Attri_text:str):
    '''
    获取父节点的bounds的xy坐标
    '''
    bounds_str=get_parent_bounds_str(path,Attri_text)
    if bounds_str is None:
        return None
    ret=get_xy_by_xy_list(xy_str_to_list(bounds_str))
    return ret

def get_current_bounds_xy(path:str,Attri_text:str):
    '''
    获取当前节点的bounds的xy坐标
    '''
    bounds_str=get_current_bounds_str(path,Attri_text)
    if bounds_str is None:
        return None
    ret=get_xy_by_xy_list(xy_str_to_list(bounds_str))
    return ret